package lagou.gateway.lagougateway.filter;

import lagou.gateway.lagougateway.utils.CacheUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class IpLimitFilter implements GlobalFilter, Ordered {


    /**
     * 次数限制
     */
       private static final Integer limitTimes=1;

    /**
     * 时间范围限制
     */
       private static final Integer timeLimit=10000;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String hostString = exchange.getRequest().getRemoteAddress().getHostString();
         ServerHttpResponse response = exchange.getResponse();
        CacheUtil cache = CacheUtil.getInstance();
       Integer times= (Integer) cache.get(hostString);
        if (null==times){
            cache.set(hostString,1,timeLimit);
        }else {
            if (times>=limitTimes){
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            String data="请求过于频繁";
                 DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }else {
             cache.set(hostString,times+1);
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
